<?php

namespace app\index\model;

use think\facade\Cache;
use think\facade\Config;
use Overtrue\EasySms\EasySms;
use Overtrue\EasySms\Exceptions\NoGatewayAvailableException;

class Sms
{
    protected $easysms;

    public function __construct()
    {
        $cfg = Config::get('easysms.');
        if(!is_array($cfg)){
            $cfg = [];
        }
        $this->easysms = new EasySms($cfg);
    }

    /**
     * 发送短信
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2019-02-15
     * @param    string             $mobile 手机号码
     * @return   Object                     FunctionResult
     */
    public function sendCode($mobile)
    {
        $app_env = Config::get('app.env');
        if($app_env == 'production'){
            $code = mt_rand(100000, 999999);
            $content = '您的验证码是'.$code.'。如非本人操作，请忽略本短信';
            $send_result = $this->sendByYunPian($mobile, $content);
        }else{
            $code = 123456;
            $send_result = new FunctionResult('短信发送成功', [], true);
        }

        if($send_result->status){
            Cache::store('redis')->set($mobile, $code, 120);
        }
        $code = Cache::store('redis')->get($mobile);
        // $send_result->pushData('code', $code);
        // $send_result->pushData('mobile', $mobile);
        return $send_result;
    }

    /**
     * 云片平台发送短信方法
     * @Author   zhanghong(Laifuzi)
     * @DateTime 2019-02-15
     * @param    string             $mobile  手机号码
     * @param    string             $content 短信内容
     * @return   Object                      FunctionResult
     */
    private function sendByYunPian($mobile, $content)
    {
        $res = new FunctionResult('短信发送失败');
        try {
            $this->easysms->send($mobile, [
                'content'  => $content,
            ]);
            $res->success('短信发送成功');
        } catch (NoGatewayAvailableException $exception) {
            $res->message = $exception->getException('yunpian')->getMessage();
        }
        return $res;
    }
}
